package com.iussoft.receiveData.filter;

import com.apache.rpc.StartSocketPortListener;
import com.apache.rpc.common.RpcUtil;
import com.apache.tools.StrUtil;
import com.iussoft.tools.LoggerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * FilterConfiguration<br>
 */
@Configuration
public class FilterConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private Environment env;

    //解决跨域请求
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
            .allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
                "Access-Control-Request-Headers")
            .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
            .allowCredentials(true).maxAge(3600);
    }

    @Bean
    public StartSocketPortListener startSocketPortListener() {
        String socketPort = StrUtil.doNull(env.getProperty("rpc.service.port"), "20808");
        String rpcVersion = env.getProperty("rpc.version");
        LoggerUtil.info("rpc.service.port->"+socketPort);
        LoggerUtil.info("rpc.version->"+rpcVersion);
        StartSocketPortListener listener = new StartSocketPortListener(socketPort);
        if (StrUtil.isNotNull(rpcVersion)) {
            RpcUtil.getInstance().setVersion(rpcVersion);
        }
        return listener;
    }

    @Bean
    public FilterRegistrationBean encodingFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new CharacterEncodingFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("encoding", "UTF-8");
        registration.addInitParameter("forceEncoding", "true");
        registration.setName("encodingFilter");
        registration.setOrder(1);
        return registration;
    }

}
